const connection = require('../app/database');

const fragment = `
  SELECT q.qid qid, q.field_id fieldId, t.type type, q.stem stem, q.options options, q.answer answer
  FROM questions q LEFT JOIN types t ON q.type_id = t.id
`;

class UserService {
  async getFieldsList(){
    const statement = `SELECT * FROM fields;`;
    const result = await connection.execute(statement);
    return result[0];
  }

  async getquestionsRand(fid, num) {
    const statement = `${fragment} WHERE field_id=? ORDER BY RAND() LIMIT ?;`;
    let result = await connection.execute(statement,[fid, num]);
    return result[0];
  }

  async getquestionsById(id){
    const statement = `${fragment} WHERE qid = ?;`;
    const questions = [];
    for(let i = 0; i < id.length; i++){
      const question = await connection.execute(statement, [id[i]]);
      questions[i] = question[0][0];
    }
    console.log(questions);
    return questions;
  }

  async getScoreList(){
    const statement = `SELECT * FROM scores;`;
    const result = await connection.execute(statement);
    return result[0];
  }

  async getScoreById(id){
    const statement = `SELECT * FROM scores WHERE id = ?;`;
    const result = await connection.execute(statement,[id]);
    return result[0];
  }

  async addScore(fid, record, score){
    const statement = ` INSERT INTO scores (field_id,record,score) VALUES(?,?,?);`
    const result = await connection.execute(statement, [fid, record, score]);
    return result[0];
  }
}

module.exports = new UserService();